<template>
    <div id="homeworkDetail" :style="style" @scroll="checkScroll">
        <div v-if="topShow" transition="fixed-top-bar">
            <div>
                <h3>{{title}}</h3>
                <p>
                    <span v-if="!isOver">截止时间 · {{overtime}}</span>
                    <span v-if="isOver">已截止</span>
                </p>
            </div>
        </div>
        <div class="float">
            <h1>作业 · 北京邮电大学图论课程网站</h1>
        </div>
        <div class="body" style="min-height: calc(100% - 30px);">
            <div class="title">
                <p v-if="!isOver">截止时间 · {{overtime}}</p>
                <p v-if="isOver">已截止</p>

                <h3>{{title}}</h3>

                <div class="article" v-if="description.length>0">
                    <p v-for="el in description" track-by="$index">{{el}}</p>
                </div>
            </div>

            <div class="content">
                <form class="upload-area" v-if="!isOver">
                    <button :id="uploadBtnId" class="add">添加文件</button>
                    <table>
                        <tr v-for="el in uploadQueue">
                            <td class="file-name"><span>{{el.name}}</span></td>
                            <td class="file-size">{{formatSize(el.size)}}</td>
                            <td class="file-delete" @click="deleteFile(el.id)">删除</td>
                        </tr>
                    </table>

                    <my-textarea :deplux.sync="detail" placeholder="备注"></my-textarea>
                    <button type="submit" @click="push($event)">提交</button>
                </form>

                <div v-for="el in pushRecord" class="record" v-if="pushRecord.length>0">
                    <h4>提交记录 {{el.created}}</h4>
                    <div class="article">
                        <p v-for="p in el.description" track-by="$index">{{p}}</p>
                    </div>
                    <div class="file">
                        {{el.name}}<span>{{formatSize(el.size)}}</span>
                    </div>
                </div>
                <div v-if="pushRecord.length==0" class="no-push">
                    没有任何提交记录
                </div>

                <!--<div v-if="imgs.length>0">-->
                <!--<img v-for="el in imgs" :src="el.path">-->
                <!--</div>-->
                <!--<div class="attachments" v-if="attachments.length>0">-->
                <!--<h2>附件</h2>-->
                <!--<div v-for="el in attachments">-->
                <!--<a :href="el.path" :download="el.path">{{el.name}}</a>-->
                <!--</div>-->
                <!--</div>-->
            </div>
        </div>

        <!--<div>-->
        <!--&lt;!&ndash;藏着触发上传用&ndash;&gt;-->
        <!--</div>-->
    </div>
</template>

<style>
    /* 必需 */
    .fixed-top-bar-transition {
        transition: all .3s ease;
        opacity: 1;
        background-color: white;
        position: fixed;
        width: 100%;
        top: 0;
        left: 0;
    }

    .fixed-top-bar-enter, .fixed-top-bar-leave {
        opacity: 0;
    }
</style>

<script type="text/babel">
    let textarea = require('../../component/input/textarea.vue');

    var Status_tab = require('../../component/sideNav/tabStatus');
    let message = require('../../component/message/message.es6');
    let modal = require('../../component/modal/modal.es6');
    let plupload = window.plupload;

    var Uploader = null;
    var vm = null;

    module.exports = {
        props: ['width', 'bannerShow', 'tab'],
        data: ()=>({
            uploadBtnId: 'homeworkDetailUploaderBtn',
            id: '',
            title: '',
            description: [],
            uploadQueue: [],
            pushRecord: [],
            overtime: '',
            detail: '',
            isOver: false,
            topShow: false
        }),
        computed: {
            style: function () {
                return {
                    'width': (this.width - 50) + 'px',
                    'left': '50px'
                }
            }
        },
        methods: {
            checkScroll: function (e) {
                this.topShow = this.$el.scrollTop > 135;
            },
            deleteFile: function (id) {
                var index = null;
                this.uploadQueue.map((v, i)=> {
                    if (v.id == id)index = i;
                });
                if (index == null)return;

                this.uploadQueue.splice(index, 1);
                var file = Uploader.getFile(id);
                Uploader.removeFile(file);
            },

            push: function (e) {
                e.preventDefault();
                if (this.uploadQueue.length == 0)return message.open('必须选择文件');
                Uploader.start();
            },

            submit: function (path) {
                modal.open('正在提交数据...');

                var file = this.uploadQueue.length > 0 && this.uploadQueue[0];
                this.$http({
                            url: '/api/homework/',
                            method: 'POST',
                            data: {
                                json: JSON.stringify({
                                    _id: this.id,
                                    file: {
                                        path: path,
                                        name: file.name,
                                        description: this.detail || '',
                                        size: file.size
                                    }
                                })
                            }
                        })
                        .then((res)=> {
                            // success callback
                            if (res.data.code == 0) {
                                modal.close();
                                message.open('提交成功!');
                                location.hash = '#!/homeworkList';
                            }
                        }, function (response) {
                            // error callback
                            return message.open('无法连接到服务器,请重试!');
                        });
            },

            //辅助方法
            formatSize: function (size) {
                var unit = ['B', 'KB', 'MB'];
                var res = '';
                if (unit.some(function (unit) {
                            if (size < 1024) {
                                return res = ('' + size).slice(0, 4).replace(/\.$/, '') + unit;
                            }
                            size = size / 1024;
                        })) {
                    return res;
                } else {
                    return 'to Large';
                }
            }
        },
        created: function () {
            vm = this;
            this.tab = Status_tab.homework;
            this.bannerShow = false;
            this.id = this.$route.params.id;
            this.$http({
                        url: '/api/homework/',
                        method: 'GET',
                        data: {
                            _id: this.id
                        }
                    })
                    .then((res)=> {
                        // success callback
                        if (res.data.code != 0)return message.open(res.data.msg);
                        let info = res.data.info;
                        console.dir(info);

                        if (new Date().getTime() > info.overtime) {
                            this.isOver = true;
                            this.overtime = `已截止`;
                        } else {
                            this.isOver = false;
                            var t = new Date(info.overtime);
                            this.overtime = `${t.getFullYear()}-${t.getMonth() + 1}-${t.getDate()}`;
                        }
                        this.pushRecord = info.files && info.files
                                        .sort((a, b)=> {
                                            return a.created < b.created;
                                        })
                                        .map(function (f) {
                                            var t = new Date(f.created);
                                            f.created = `${t.getFullYear()}-${t.getMonth() + 1}-${t.getDate()} ${t.getHours()}:${t.getMinutes()}:${t.getSeconds()}`;
                                            f.description = f.description.length > 0 && f.description.split('\n') || [];
                                            return f;
                                        }) || [];
                        this.description = info.description.length > 0 && info.description.split('\n') || [];
                        this.title = info.title;

                        let overtime = new Date(info.overtime);
                        this.created = '截止至' + ` ${overtime.getFullYear()}-${overtime.getMonth() + 1}-${overtime.getDate()}`;

                    }, function (response) {
                        // error callback
                        location.hash = '#!/homeworkList/';
                        return message.open('无法连接到服务器,请重试!');
                    });
        },
        ready: function () {
            Uploader = new plupload.Uploader({
                browse_button: this.uploadBtnId, //触发文件选择对话框的按钮，为那个元素id
                url: '/file/upload', //服务器端的上传页面地址
                multi_selection: false
            });
            Uploader.init();

            Uploader.bind('FilesAdded', function (uploader, files) {
                //只允许上传一个文件
//                files.map((file)=> {
//                    vm.uploadQueue.push(file);
//                })
                vm.uploadQueue = files;
            });

            Uploader.bind('UploadProgress', function (uploader, file) {
                modal.open(`正在上传文件... ${Uploader.total.percent}%`);
            });

            Uploader.bind('FileUploaded', function (uploader, file, res) {
                var data = JSON.parse(res.response).file;
                vm.submit(data.path);
            });
        },
        route: {
            deactivate: function (transition) {
                vm = null;
                Uploader.destroy();
                transition.next();
            }
        },
        components: {
            'my-textarea': textarea
        }
    }
</script>